package com.sakura.controller;

import com.sakura.dto.*;
import com.sakura.entity.Manager;
import com.sakura.service.ManagerService;
import com.sakura.util.EntityConverter;
import com.sakura.util.R;
import com.sakura.vo.ManagerSelectVO;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.groupingBy;


/**
 * @author : Sakura
 * @Date : 2023/11/22 16:11
 * @Description 管理员表
 */
@Api(value = "/", tags = {"管理员表"})
@RestController
@RequestMapping("/api/manager")
//解决跨域问题
@CrossOrigin
@Slf4j
public class ManagerController {

    @Autowired

    private ManagerService managerService;

    /**
     * 根据名称查询管理员
     *
     * @return R
     * @author Sakura
     * @date 2023/11/22 16:41
     */
    @ApiOperation(value = "管理员分页查询", notes = "管理员分页查询")
    @PostMapping("/list")
    public R list(@ApiParam(type = "QueryManagerDTO" , value = "查询条件") @RequestBody QueryManagerDTO managerDTO) {
        return R.success(managerService.getPage(managerDTO));
    }


    /**
     * 添加或者修改管理员
     *
     * @param managerDTO:
     * @return R
     * @author Sakura
     * @date 2023/11/22 17:26
     */
    @ApiOperation(value = "添加或者修改管理员", notes = "添加或者修改管理员", httpMethod = "POST")
    @PostMapping("/saveOrUpdate")
    public R addOrUpdate(@ApiParam(value = "添加或者修改管理员", type = "InsertOrUpdateManagerDTO", required = true) @RequestBody InsertOrUpdateManagerDTO managerDTO) {
        //等于null则是添加
        Manager manager = EntityConverter.copyAndGetSingle(managerDTO, Manager.class);
        boolean result = false;
        if (managerDTO.getId() == null || managerDTO.getId() == 0) {
            setAvatarUrl(manager);
            result = managerService.save(manager);
            return getResult(result);
        }
        //不为null则是修改
        manager.setUpdateTime(new Date());
        setAvatarUrl(manager);
        result = managerService.updateById(manager);
        return getResult(result);
    }

    private void setAvatarUrl(Manager manager) {
        if (manager.getAvatar() != null&&!manager.getAvatar().contains("https://")) {
            String prefix = "http://localhost:8081/api/image/download?name=";
            manager.setAvatar(prefix + manager.getAvatar());
        }
    }

    /**
     * 将执行结果返回给前端
     *
     * @param result:
     * @return R<?>
     * @author Sakura
     * @date 2023/11/22 18:33
     */
    private R<?> getResult(boolean result) {
        if (!result) {
            return R.error("操作失败，请重新尝试");
        }
        return R.success("操作成功");
    }

    /**
     * 根据id删除网格员
     *
     * @param id:
     * @return R
     * @author Sakura
     * @date 2023/11/22 19:04
     */
    @ApiOperation(value = "根据id删除网格员", notes = "根据id删除网格员", httpMethod = "DELETE")
    @DeleteMapping("/delete/{id}")
    public R delete(@ApiParam(value = "网格员id", required = true) @PathVariable Long id) {
        boolean result = managerService.removeById(id);
        return getResult(result);
    }

    @ApiOperation(value = "根据集合删除网格员", notes = "根据集合删除网格员")
    @DeleteMapping("/batch")
    public R delete(@ApiParam(value = "网格员集合id", required = true) @RequestBody List<Long> ids) {
        if (ids.size() == 0) {
            return R.error("请选择要删除的网格员");
        }
        boolean result = managerService.removeByIds(ids);
        return getResult(result);
    }

    /**
     * 根据id查找网格员
     *
     * @param id:
     * @return R
     * @author Sakura
     * @date 2023/11/22 19:06
     */
    @ApiOperation(value = "根据id查找网格员", notes = "根据id查找网格员", httpMethod = "GET")
    @GetMapping("/query/{id}")
    public R queryOne(@ApiParam(value = "网格员id", required = true) @PathVariable Long id) {
        return R.success(managerService.getById(id));
    }


    /**
     * 管理员，网格员登录接口
     * @param loginDTO:
     * @return R
     * @author Sakura
     * @date 2023/11/23 9:14
     */
    @PostMapping("/login")
    @ApiOperation(value = "管理员，网格员登录", notes = "管理员，网格员登录")
    public R login(@ApiParam(value = "管理员网格员登录实体类", required = true) @RequestBody ManagerLoginDTO loginDTO) {
        return managerService.login(loginDTO);
    }

    /**
     * 管理员，网格员注册接口
     * @param registerDTO: 注册管理员
     * @return R
     * @author Sakura
     * @date 2023/11/23 9:14
     */
    @PostMapping("/register")
    @ApiOperation(value = "管理员，网格员注册", notes = "管理员，网格员注册")
    public R register(@ApiParam(value = "管理员网格员注册实体类", required = true) @RequestBody InsertOrUpdateManagerDTO registerDTO) {
        return managerService.register(registerDTO);
    }

    @PostMapping("/currentUser")
    @ApiOperation(value = "获取当前登录用户", notes = "获取当前登录用户")
    public R getCurrentUser(@ApiParam(value = "获取当前登录用户", required = true) @RequestBody ManagerDTO managerDTO) {
        return R.success(managerService.getById(managerDTO.getId()));
    }

    @PostMapping("/logout")
    @ApiOperation(value = "管理员，网格员退出登录", notes = "管理员，网格员退出登录")
    public R logout(@ApiParam(value = "管理员网格员退出登录实体类", required = true) @RequestBody ManagerDTO managerDTO) {
        log.info("管理员 {} 退出登录" ,managerDTO.getId());
        return managerService.logout(managerDTO);
    }
    @ApiOperation(value = "网格员下拉选择", notes = "网格员下拉选择")
    @GetMapping("/select")
    public R select() {
        List<Manager> managers = managerService.list();
        List<ManagerSelectVO> managerSelectDTOS = managers.stream().map(item -> {
            ManagerSelectVO managerSelectDTO = new ManagerSelectVO();
            managerSelectDTO.setId(item.getId());
            managerSelectDTO.setName(item.getName());
            return managerSelectDTO;
        }).collect(Collectors.toList());
        return R.success(managerSelectDTOS);
    }

    @GetMapping("/login/captcha")
    @ApiOperation(value = "登录获取验证码", notes = "登录获取验证码")
    public R captcha(@ApiParam(value = "手机号", required = true) @RequestParam("phone") String phone) {
        return managerService.getCaptcha(phone);
    }
}
